package cn.tedu.ssm.Controller;

import cn.tedu.ssm.pojo.User;
import cn.tedu.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 分页查询数据
     */
    @GetMapping("list")
    public Map<String, Object> list(@RequestParam(name = "page", required = false) Integer page, @RequestParam(name = "size",required = false) Integer size){
        return userService.list(page, size);
    }

    /**
     * 查询所有非删除用户的姓名和禁用状态
     */
    @GetMapping("user-edit")
    public Map<String,Object> userList(){
        return userService.findNameAndDisabled();
    }

    @GetMapping("userAdd")
    public Integer userAdd(@RequestParam(value = "name",required = false) String name,@RequestParam(value = "username",required = false) String username,@RequestParam(value = "password",required = false) String password){
        return userService.userAdd(name,username,password);
    }

    @GetMapping("getUser")
    public Map<String, String> getuser(HttpServletRequest request) throws IOException {
        Map<String, String> map = new HashMap<>();
        HttpSession session = request.getSession();
        if (session.getAttribute("name") == null){
            return map;
//            return "";
        }
        map.put("name",String.valueOf(session.getAttribute("name")));
        return map;
    }

    @GetMapping("userId")
    public Long getUserId(@RequestParam(name = "username",required = false) String username){
        return userService.findIdByUsername(username);
    }

    @GetMapping("userCount")
    public Long getUserCount(){
        try{
            return userService.userCount();
        }catch (Exception e){
            return 0L;
        }
    }

    @GetMapping("getUserInfo")
    public Map<String, Object> findInfoById(Long id){
        Map<String, Object> map = new HashMap<>();
        User info = userService.findInfoById(id);
        if (info != null){
            map.put("user",info);
        }
        return map;
    }

    @RequestMapping("updateUser")
    public Long updateUser(Long id, String name, String password){
        if (id>0 && name != null && password != null){
            return userService.updateUser(id, name, password);
        }
        return 0L;
    }
}